package vip.xiaonuo.biz.modular.event.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSON;
import org.apache.commons.lang3.StringUtils;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import vip.xiaonuo.biz.modular.cabinetdoor.mapper.BizCabinetDoorMapper;
import vip.xiaonuo.biz.modular.cabinetdoor.vo.BizCabinetDoorResp;
import vip.xiaonuo.biz.modular.cabinetinfo.entity.BizCabinetInfo;
import vip.xiaonuo.biz.modular.cabinetinfo.mapper.BizCabinetInfoMapper;
import vip.xiaonuo.biz.modular.event.entity.BizEvent;
import vip.xiaonuo.biz.modular.event.service.BizEventReplaceService;
import vip.xiaonuo.biz.modular.goods.entity.BizGoods;
import vip.xiaonuo.biz.modular.goods.result.GoodsLedgerPageResult;
import vip.xiaonuo.biz.modular.relation.enums.BizRelationCategoryEnum;
import vip.xiaonuo.biz.modular.relation.service.BizRelationService;
import vip.xiaonuo.biz.modular.user.entity.BizUser;
import vip.xiaonuo.biz.modular.user.mapper.BizUserMapper;
import vip.xiaonuo.common.util.AliyunSmsUtil;
import vip.xiaonuo.common.util.CommonPhoneUtil;
import vip.xiaonuo.dev.api.DevEmailApi;
import vip.xiaonuo.dev.api.DevSmsApi;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author 墨塵
 * @since 2022/12/2
 */
@Service
@Transactional
public class BizEventReplaceServiceImpl implements BizEventReplaceService {

    @Resource
    private BizUserMapper bizUserMapper;

    @Resource
    private BizCabinetInfoMapper bizCabinetInfoMapper;

    @Resource
    private BizCabinetDoorMapper bizCabinetDoorMapper;

    @Resource
    private DevEmailApi devEmailApi;

    @Resource
    private DevSmsApi devSmsApi;

    @Resource
    private BizRelationService bizRelationService;

    @Override
    public String getCabName(String cabCode) {
        String result = "[未知柜子]";
        BizCabinetInfo info = bizCabinetInfoMapper.getInfoByCode(cabCode);
        if (null != info) {
            result = info.getCabinetName() + "[" + info.getCabinetCode() + "]";
        }
        return result;
    }

    @Override
    public BizCabinetInfo getCabInfo(String cabCode) {
        return bizCabinetInfoMapper.getInfoByCode(cabCode);
    }

    @Override
    public String getUserName(String userId) {
        String result = "[未知用户]";
        if (StringUtils.isNotBlank(userId)) {
            BizUser user = bizUserMapper.selectById(userId);
            if (null != user) {
                result = user.getName() + "[" + user.getAccount() + "]";
            }
        }
        return result;
    }

    @Override
    public String getGoodsNameForEntity(BizGoods goods) {
        String result = "[未知物品]";
        if (null != goods) {
            if (StringUtils.isNotBlank(goods.getGoodsName())) {
                result = goods.getGoodsName();
                if (StringUtils.isNotBlank(goods.getGoodsCode())) {
                    result = result + "[" + goods.getGoodsCode() + "]";
                }
                if (StringUtils.isNotBlank(goods.getReagentCasNo())) {
                    result = result + "[" + goods.getReagentCasNo() + "]";
                }
            }
        }
        return result;
    }

    @Override
    public String getGoodsNameForLedger(GoodsLedgerPageResult ledgerPageResult) {
        String result = "[未知物品]";
        if (null != ledgerPageResult) {
            if (StringUtils.isNotBlank(ledgerPageResult.getGoodsName())) {
                result = ledgerPageResult.getGoodsName();
                if (StringUtils.isNotBlank(ledgerPageResult.getGoodsCode())) {
                    result = result + "[" + ledgerPageResult.getGoodsCode() + "]";
                }
                if (StringUtils.isNotBlank(ledgerPageResult.getReagentCas())) {
                    result = result + "[" + ledgerPageResult.getReagentCas() + "]";
                }
            }
        }
        return result;
    }

    @Override
    public String getCbaDoorNameForCode(String cabCode, String cabDoorCode) {
        String result = "[未知柜门]";
        BizCabinetDoorResp info = bizCabinetDoorMapper.getInfoByCabCodeAndCabDoorCode(cabCode, cabDoorCode);
        if (null != info) {
            result = info.getCabinetName() + "[" + info.getCabinetCode() + "]-" + info.getCabinetDoorName() + "[" + info.getCabinetDoorCode() + "]";
        }
        return result;
    }

    @Override
    public String getCbaDoorNameForId(String cabId, String cabDoorId) {
        String result = "[未知柜门]";
        BizCabinetDoorResp info = bizCabinetDoorMapper.getInfoByCabIdAndCabDoorId(cabId, cabDoorId);
        if (null != info) {
            result = info.getCabinetName() + "[" + info.getCabinetCode() + "]-" + info.getCabinetDoorName() + "[" + info.getCabinetDoorCode() + "]";
        }
        return result;
    }

    @Override
    public BizCabinetDoorResp getCbaDoorRespForCode(String cabCode, String cabDoorCode) {
        return bizCabinetDoorMapper.getInfoByCabCodeAndCabDoorCode(cabCode, cabDoorCode);
    }

    @Override
    public BizCabinetDoorResp getCbaDoorRespForId(String cabId, String cabDoorId) {
        return bizCabinetDoorMapper.getInfoByCabIdAndCabDoorId(cabId, cabDoorId);
    }

    @Override
    public void clearBizEvent(BizEvent event) {
        event.setId(null);
        event.setCreateUser(null);
        event.setCreateTime(null);
        event.setUpdateUser(null);
        event.setUpdateTime(null);
    }

    @Override
    @Async("hxunicornAsyncServiceExecutor")
    public void sendEmailForUser(String userId, BizEvent event) {
        if (StringUtils.isNotBlank(userId)) {
            BizUser bizUser = bizUserMapper.selectById(userId);
            if (bizUser != null) {
                if (StringUtils.isNotBlank(bizUser.getEmail())) {
                    devEmailApi.sendHtmlEmailLocal(bizUser.getEmail(), event.getEventTitle(), event.getEventDesc(), null, CollectionUtil.newArrayList(), event.getId(), userId, event.getEventCode());
                }
            }
        }
    }

    @Override
    @Async("hxunicornAsyncServiceExecutor")
    public void sendEmailForDoorAdmin(BizEvent event) {
        List<String> adminList = new ArrayList<>();
        if (StringUtils.isNotBlank(event.getCabinetDoorId())) {
            //柜门管理员
            List<String> cabinetDoorAdminIds = bizRelationService.getRelationTargetIdListByObjectIdAndCategory(event.getCabinetDoorId(), BizRelationCategoryEnum.BIZ_RELATION_CABINET_DOOR_AND_ADMIN_USER.getValue());
            adminList = cabinetDoorAdminIds;
            if (adminList.isEmpty()) {
                if (StringUtils.isNotBlank(event.getCabinetId())) {
                    //柜子管理员
                    List<String> cabinetAdminIds = bizRelationService.getRelationTargetIdListByObjectIdAndCategory(event.getCabinetId(), BizRelationCategoryEnum.BIZ_RELATION_CABINET_INFO_AND_ADMIN_USER.getValue());
                    adminList = cabinetAdminIds;
                }
            }
            if (adminList.isEmpty()) {
                if (StringUtils.isNotBlank(event.getCabinetGroupId())) {
                    //柜组管理员
                    List<String> cabinetGroupAdminIds = bizRelationService.getRelationTargetIdListByObjectIdAndCategory(event.getCabinetGroupId(), BizRelationCategoryEnum.BIZ_RELATION_CABINET_GROUP_AND_ADMIN_USER.getValue());
                    adminList = cabinetGroupAdminIds;
                }
            }
            if (!adminList.isEmpty()) {
                //拆分为单人发送邮件
                for (String adminId : adminList) {
                    BizUser bizUser = bizUserMapper.selectById(adminId);
                    if (null != bizUser) {
                        if (StringUtils.isNotBlank(bizUser.getEmail())) {
                            devEmailApi.sendHtmlEmailLocal(bizUser.getEmail(), event.getEventTitle(), event.getEventDesc(), null, CollectionUtil.newArrayList(), event.getId(), adminId, event.getEventCode());
                        }
                    }
                }
                //获取邮箱集合 (为了取消订阅)
//                String emails = bizUserMapper.getEmailsByIds(adminList);
//                if (StringUtils.isNotBlank(emails)) {
//                    devEmailApi.sendHtmlEmailLocal(emails, event.getEventTitle(), event.getEventDesc(), null, CollectionUtil.newArrayList(), event.getId());
//                }
            }
        }
    }

    @Override
    @Async("hxunicornAsyncServiceExecutor")
    public void sendEmailForCabAdmin(BizEvent event) {
        List<String> adminList = new ArrayList<>();
        if (StringUtils.isNotBlank(event.getCabinetId())) {
            //柜子管理员
            List<String> cabinetAdminIds = bizRelationService.getRelationTargetIdListByObjectIdAndCategory(event.getCabinetId(), BizRelationCategoryEnum.BIZ_RELATION_CABINET_INFO_AND_ADMIN_USER.getValue());
            adminList = cabinetAdminIds;
            if (adminList.isEmpty()) {
                if (StringUtils.isNotBlank(event.getCabinetGroupId())) {
                    //柜组管理员
                    List<String> cabinetGroupAdminIds = bizRelationService.getRelationTargetIdListByObjectIdAndCategory(event.getCabinetGroupId(), BizRelationCategoryEnum.BIZ_RELATION_CABINET_GROUP_AND_ADMIN_USER.getValue());
                    adminList = cabinetGroupAdminIds;
                }
            }
            if (!adminList.isEmpty()) {
                //拆分为单人发送邮件
                for (String adminId : adminList) {
                    BizUser bizUser = bizUserMapper.selectById(adminId);
                    if (null != bizUser) {
                        if (StringUtils.isNotBlank(bizUser.getEmail())) {
                            devEmailApi.sendHtmlEmailLocal(bizUser.getEmail(), event.getEventTitle(), event.getEventDesc(), null, CollectionUtil.newArrayList(), event.getId(), adminId, event.getEventCode());
                        }
                    }
                }
                //获取邮箱集合 (为了取消订阅)
//                String emails = bizUserMapper.getEmailsByIds(adminList);
//                if (StringUtils.isNotBlank(emails)) {
//                    devEmailApi.sendHtmlEmailLocal(emails, event.getEventTitle(), event.getEventDesc(), null, CollectionUtil.newArrayList(), event.getId());
//                }
            }
        }
    }

    @Override
    @Async("hxunicornAsyncServiceExecutor")
    public void sendSmsForUser(String userId, BizEvent event, String smsId, Map<String, String> content) {
        if (StringUtils.isNotBlank(userId)) {
            BizUser bizUser = bizUserMapper.selectById(userId);
//            if (bizUser != null) {
//                if (StringUtils.isNotBlank(bizUser.getPhone())) {
//                    if (CommonPhoneUtil.verifyPhone(bizUser.getPhone())) {
//                        devSmsApi.sendSmsAliyun(bizUser.getPhone(), null, smsId, JSON.toJSONString(content), event.getId());
//                    }
//                }
//            }
            this.sendSmsHKUST(bizUser, smsId, content, event.getId());
        }
    }

    @Override
    @Async("hxunicornAsyncServiceExecutor")
    public void sendSmsForDoorAdmin(BizEvent event, String smsId, Map<String, String> content) {
        List<String> adminList = new ArrayList<>();
        if (StringUtils.isNotBlank(event.getCabinetDoorId())) {
            //柜门管理员
            List<String> cabinetDoorAdminIds = bizRelationService.getRelationTargetIdListByObjectIdAndCategory(event.getCabinetDoorId(), BizRelationCategoryEnum.BIZ_RELATION_CABINET_DOOR_AND_ADMIN_USER.getValue());
            adminList = cabinetDoorAdminIds;
            if (adminList.isEmpty()) {
                if (StringUtils.isNotBlank(event.getCabinetId())) {
                    //柜子管理员
                    List<String> cabinetAdminIds = bizRelationService.getRelationTargetIdListByObjectIdAndCategory(event.getCabinetId(), BizRelationCategoryEnum.BIZ_RELATION_CABINET_INFO_AND_ADMIN_USER.getValue());
                    adminList = cabinetAdminIds;
                }
            }
            if (adminList.isEmpty()) {
                if (StringUtils.isNotBlank(event.getCabinetGroupId())) {
                    //柜组管理员
                    List<String> cabinetGroupAdminIds = bizRelationService.getRelationTargetIdListByObjectIdAndCategory(event.getCabinetGroupId(), BizRelationCategoryEnum.BIZ_RELATION_CABINET_GROUP_AND_ADMIN_USER.getValue());
                    adminList = cabinetGroupAdminIds;
                }
            }
            if (!adminList.isEmpty()) {
//                //获取手机号集合
//                String phones = bizUserMapper.getPhonesByIds(adminList);
//                if (StringUtils.isNotBlank(phones)) {
//                    //过滤非手机号的
//                    List<String> phoneList = Arrays.asList(phones.split(",")).stream().filter(item -> CommonPhoneUtil.verifyPhone(item)).collect(Collectors.toList());
//                    devSmsApi.sendSmsAliyun(String.join(",", phoneList), null, smsId, JSON.toJSONString(content), event.getId());
//                }
                for (String adminId : adminList) {
                    BizUser bizUser = bizUserMapper.selectById(adminId);
                    this.sendSmsHKUST(bizUser, smsId, content, event.getId());
                }
            }
        }
    }

    @Override
    @Async("hxunicornAsyncServiceExecutor")
    public void sendSmsForCabAdmin(BizEvent event, String smsId, Map<String, String> content) {
        List<String> adminList = new ArrayList<>();
        if (StringUtils.isNotBlank(event.getCabinetId())) {
            //柜子管理员
            List<String> cabinetAdminIds = bizRelationService.getRelationTargetIdListByObjectIdAndCategory(event.getCabinetId(), BizRelationCategoryEnum.BIZ_RELATION_CABINET_INFO_AND_ADMIN_USER.getValue());
            adminList = cabinetAdminIds;
            if (adminList.isEmpty()) {
                if (StringUtils.isNotBlank(event.getCabinetGroupId())) {
                    //柜组管理员
                    List<String> cabinetGroupAdminIds = bizRelationService.getRelationTargetIdListByObjectIdAndCategory(event.getCabinetGroupId(), BizRelationCategoryEnum.BIZ_RELATION_CABINET_GROUP_AND_ADMIN_USER.getValue());
                    adminList = cabinetGroupAdminIds;
                }
            }
            if (!adminList.isEmpty()) {
//                //获取手机号集合
//                String phones = bizUserMapper.getPhonesByIds(adminList);
//                if (StringUtils.isNotBlank(phones)) {
//                    //过滤非手机号的
//                    List<String> phoneList = Arrays.asList(phones.split(",")).stream().filter(item -> CommonPhoneUtil.verifyPhone(item)).collect(Collectors.toList());
//                    devSmsApi.sendSmsAliyun(String.join(",", phoneList), null, smsId, JSON.toJSONString(content), event.getId());
//                }
                for (String adminId : adminList) {
                    BizUser bizUser = bizUserMapper.selectById(adminId);
                    this.sendSmsHKUST(bizUser, smsId, content, event.getId());
                }
            }
        }
    }

    @Override
    public void itemSwitch(BizEvent event, Integer goodsType) {
        if (null != goodsType) {
            String title = event.getEventTitle();
            String desc = event.getEventDesc();
            if (goodsType == 1) {
                event.setEventTitle(title.replaceAll("物品", "试剂"));
                event.setEventDesc(desc.replaceAll("物品", "试剂"));
            }
        }
    }

    private void sendSmsHKUST(BizUser bizUser, String smsId, Map<String, String> content, String eventId) {
        String smsContent = AliyunSmsUtil.getSmsCry(smsId, content);
        if (null != bizUser) {
            if (bizUser.getUserType() == 1 || bizUser.getUserType() == 2) {
                //内部用户拿ACCOUNT
                if (StringUtils.isNotBlank(bizUser.getAccount())) {
                    devSmsApi.sendSmsHKUST(Arrays.asList(bizUser.getAccount()), null, smsContent, eventId);
                }
            } else {
                //外部用户拿PHONE
                if (StringUtils.isNotBlank(bizUser.getPhone())) {
                    //校验下手机号
                    if (CommonPhoneUtil.verifyPhone(bizUser.getPhone())) {
                        devSmsApi.sendSmsHKUST(null, Arrays.asList(bizUser.getPhone()), smsContent, eventId);
                    }
                }
            }
        }
    }
}
